<template>
  <div class="partake">
    <el-form
      ref="form"
      :inline="true"
      class="demo-form-inline"
      :model="queryParams"
    >
      <el-form-item label="查找" prop="dpAccount">
        <el-input
          clearable
          v-model="queryParams.dpAccount"
          placeholder="请输入大鹏号"
          size="small"
          class="numberInput"
        ></el-input>
      </el-form-item>
      <el-form-item label="活动周期" prop="stageId" class="right">
        <el-select
          v-model="queryParams.stageId"
          size="small"
          clearable
          placeholder="请选择"
          style="width:240px"
        >
          <template v-for="item in activeStatus">
            <el-option
              v-if="
                item.stageStatus !== 'NOT_STARTED' &&
                  item.stageStatus !== 'NOT_START'
              "
              :key="item.id"
              :label="item.flowerStageName"
              :value="item.id"
            ></el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item class="s-btn">
        <el-button type="success" icon="el-icon-search" @click="toSearch()">
          查询
        </el-button>
        <el-button type="success" plain @click="reset"> 重置 </el-button>
      </el-form-item>
    </el-form>
    <!-- 按钮 -->
    <div class="btn-box">
      <el-row>
        <el-col :span="20">
          <el-button type="success" @click="handleReward" size="medium"
            >奖励</el-button
          >
          <el-button type="success" @click="handleTabs" size="medium"
            >奖励记录</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="success" size="medium" @click="exportFile"
            >导出</el-button
          >
          <freshCom @searchList="searchList"></freshCom>
        </el-col>
      </el-row>
    </div>
    <!-- table -->
    <el-table
      id=""
      v-loading="loading"
      :data="tableData"
      border
      style="width: 96%"
      max-height="700"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        label="全选"
        width="55"
        align="center"
      />
      <el-table-column
        label="用户昵称"
        align="left"
        prop="user.userName"
        width="210"
      >
      </el-table-column>
      <el-table-column
        label="大鹏号"
        align="left"
        prop="user.dpAccount"
        width="210"
      ></el-table-column>
      <el-table-column
        label="手机号"
        align="left"
        prop="user.mobile"
        width="210"
      ></el-table-column>
      <el-table-column
        label="活动周期"
        align="left"
        prop="stagesNames"
        width="210"
      >
        <template slot-scope="scope">
          <div style="text-align: left">
            <span>{{ scope.row.stagesNames }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="参与时间"
        align="left"
        prop="createdTime"
        width="210"
      >
        <template slot-scope="scope">
          <div style="text-align: left">
            <span>{{ scope.row.createdTime }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="鲜花数"
        align="left"
        prop="getFlowersCount"
        width="210"
      >
        <template slot-scope="scope">
          <div style="text-align: left">
            <span>鲜花{{ scope.row.getFlowersCount }}朵</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="名次" align="center" prop="rank" width="210">
        <template slot-scope="scope">
          <div style="text-align: center">
            <span>{{ scope.row.rank }}</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-全局组件-->
    <pageCom
      :searchParams="searchParams"
      :total="total"
      @searchList="searchList"
    ></pageCom>
    <!-- 弹窗 -->
    <!-- 奖励鲜花弹窗 -->
    <div class="dialogReward">
      <el-dialog
        :title="'奖励鲜花'"
        width="600px"
        :visible="rwardData.isShow"
        center
        :close-on-click-modal="false"
        @close="rewardClose"
      >
        <el-form ref="form" class="demo-form-inline" :model="rewardForm">
          <el-form-item label="已勾选用户数" prop="name">
            <div>{{ rewardForm.userNum }}</div>
          </el-form-item>
          <el-form-item label="奖励鲜花数" prop="flowerNum">
            <el-input-number
              v-model="rewardForm.flowerNum"
              size="small"
              controls-position="right"
              :max="99999"
              :precision="0"
              :min="0"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="奖励商品" prop="partakeGoods">
            <el-button
              type="success"
              size="medium"
              round
              @click="handlegoodsList"
              >选择商品</el-button
            >
            <!-- 选中商品展示 -->
            <div class="show-goods-box">
              <div
                class="show-goods"
                v-for="(item, index) in selectGoods"
                :key="index"
              >
                <div class="img">
                  <i
                    class="el-icon-error img-btn"
                    @click.prevent="delGoods(item.id)"
                  ></i>
                  <img :src="item.imgJson[0].url" alt="" />
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            type="success"
            size="medium"
            @click="handleSavePartakeGoods"
            >确认</el-button
          >
          <el-button size="medium" @click="partakeGoodsOnCancel"
            >取消</el-button
          >
        </div>
        <!-- 选择商品弹窗 -->
        <el-dialog
          width="70%"
          title="选择商品"
          :visible.sync="goodsDialog.isShow"
          append-to-body
          @close="goodsClose"
          class="goods"
        >
          <el-table
            class="goods-data"
            :data="goodsData"
            height="500"
            border
            style="width: 100%"
            ref="table"
            @selection-change="handleGoodsSelectionChange"
          >
            <el-table-column
              type="selection"
              width="55"
              align="center"
              :selectable="selectAble"
            />
            <el-table-column
              label="序号"
              type="index"
              align="center"
              width="50"
            >
            </el-table-column>
            <el-table-column label="商品名称" align="center" prop="name">
            </el-table-column>
            <el-table-column
              label="商品缩略图"
              align="center"
              prop="view"
              min-width="30"
            >
              <template slot-scope="scope">
                <listImgShow :imgInfo="scope.row.imgJson"></listImgShow>
              </template>
            </el-table-column>
            <el-table-column label="所需鲜花" align="center" prop="price">
            </el-table-column>
          </el-table>
          <div class="page-box">
            <pageCom
              :searchParams="goodsParams"
              :total="goodsTotal"
              @searchList="handlegoodsList"
            ></pageCom>
          </div>

          <div slot="footer" class="dialog-footer">
            <el-button type="success" size="medium" @click="handleSaveGoods"
              >确认</el-button
            >
            <el-button size="medium" @click="goodsOnCancel">取消</el-button>
          </div>
        </el-dialog>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getStages,
  getPartakeList,
  getgoodsList,
  addUserAwards,
  partakeExport
} from '@/api/flowerActive/partakeReward/index'
import { reqUrl } from '../../../../utils/public'
export default {
  data() {
    return {
      queryParams: {
        dpAccount: '', // 查找大鹏用户
        stageId: ''
      },
      activeStatus: [],
      loading: true,
      //  loading: true,
      // 总条数
      total: 0,
      // 分页数据
      searchParams: {
        pageNum: 1, // 当前页数
        pageSize: 10 // 页面显示条数
      },
      // table参数
      tableData: [],
      // 非多个禁用
      multiple: true,
      // 存放选中表格用户数量
      ids: [],
      // 选中的商品id
      goodId: [],
      selectGoods: [],
      temp: [],
      // 奖励鲜花弹窗变量
      rwardData: {
        isShow: false, // 默认隐藏
        params: '',
        total: ''
      },
      // 弹窗表单
      rewardForm: {
        userNum: '',
        flowerNum: '', //鲜花数量
        partakeGoods: ''
      },
      addModel: {
        awardDetails: {
          awards: [],
          flowerNumber: 0
        },
        userInfoAddModels: []
      },
      // 商品弹窗
      goodsDialog: {
        isShow: false // 默认隐藏
      },
      // 商品列表
      // 奖品类型[VIRTUAL_PRIZE:虚拟奖品/PHYSICALS_PRIZE:实物奖品]
      goodsData: [],
      // 弹窗分页
      goodsParams: {
        pageNum: 1, // 当前页数
        pageSize: 10 // 页面显示条数
      },
      // 弹窗分页总数
      goodsTotal: 0
    }
  },
  async created() {
    // 调用获取活动周期方法
    await this.getStages(this.$route.query.id)
  },
  methods: {
    // 活动周期
    getStages(id) {
      getStages(id, (res) => {
        this.activeStatus = res
      })
    },
    // 顶部查询功能
    toSearch() {
      this.searchParams.pageNum = 1
      this.searchList()
    },
    // 置灰功能
    selectAble(row, index) {
      if (this.selectGoods.length > 0) {
        if (
          this.selectGoods.some((el) => {
            return el.id === row.id
          })
        ) {
          return false
        } else {
          return true
        }
      } else {
        return true
      }
    },
    // 获取列表
    searchList() {
      let id = this.$route.query.id
      let params = {
        ...this.searchParams,
        ...this.queryParams
      }
      getPartakeList(id, params, (res) => {
        if (res.rows) {
          this.tableData = res.rows
          this.total = res.total
        }
        this.loading = false
      })
    },
    handleSelectionChange(selection) {
      // 置空上次所选数据
      this.addModel.userInfoAddModels = []
      // 写入要奖励人的用户信息
      selection.forEach((item) => {
        this.addModel.userInfoAddModels.push({
          dpAccount: item.user.dpAccount,
          mobile: item.user.mobile,
          rank: item.user.rank,
          stageId: item.flowerActivityStageId,
          userId: item.user.userId,
          userName: item.user.userName
        })
      })

      // 选中表格用户数量
      this.ids = selection.map((item) => item.id)
      this.multiple = !selection.length
    },
    // 商品表格，限制单选
    handleGoodsSelectionChange(selection) {
      this.temp = []
      this.temp.push(...selection)
      // this.goodId = selection.map((item) => item.id)
    },
    // 奖励鲜花弹窗
    handleReward() {
      if (this.ids.length === 0) {
        this.$message.error('请至少选择一条用户数据')
        return
      } else {
        this.$set(this.rewardForm, 'userNum', this.ids.length)
        if (this.rewardForm.flowerNum !== 0) {
          this.$set(this.rewardForm, 'flowerNum', 0)
        }
        this.rwardData.isShow = true
        // //对象去重
        // let obj = {}
        // this.addModel.userInfoAddModels = this.addModel.userInfoAddModels.reduce(function (item, next) {
        //   obj[next.dpAccount] ? '' : (obj[next.dpAccount] = true && item.push(next))
        //   return item
        // }, [])
        // 清空上次所选商品
        this.selectGoods = []
      }
    },
    // 切换到奖励记录
    handleTabs() {
      this.$parent.tabChange(1)
    },
    // 奖励鲜花弹窗关闭
    rewardClose() {
      this.rwardData.isShow = false
    },
    // 打开商品弹窗
    handlegoodsList() {
      let params = { ...this.goodsParams }
      getgoodsList(params, (res) => {
        if (res.rows) {
          this.goodsData = res.rows
          this.goodsTotal = res.total
          this.goodsData.forEach((item, index) => {
            this.$set(item, 'imgJson', [])
            item.imgJson.push({
              url: item.image
            })
          })
        }
      })
      this.goodsDialog.isShow = true
    },
    // 关闭商品弹窗
    goodsClose() {
      this.goodsDialog.isShow = false
    },
    // 奖励鲜花 保存功能
    handleSavePartakeGoods() {
      // this.$message({
      //   message:
      //     '你的作品在”{活动名称}“活动中排名第{名次}名，获得了奖励名称，赶紧去”大鹏教育“APP查看吧。',
      //   type: 'success',
      // })
      this.addModel.awardDetails.awards = []
      // 循环添加奖励商品
      this.selectGoods.forEach((item) => {
        this.addModel.awardDetails.awards.push({
          id: item.id,
          name: item.name,
          number: item.price
        })
      })
      this.addModel.awardDetails.flowerNumber = this.rewardForm.flowerNum
      if (
        this.addModel.awardDetails.flowerNumber != 0 ||
        this.addModel.awardDetails.awards.length > 0
      ) {
        let params = { ...this.addModel }
        addUserAwards(this.$route.query.id, params, (res) => {
          this.rewardClose()
          // 刷新列表
          this.searchList()
        })
      } else {
        this.$message.error('请您设置奖品')
      }
    },
    // 奖励鲜花 取消功能
    partakeGoodsOnCancel() {
      this.rewardClose()
    },
    // 选中的商品
    handleSaveGoods() {
      if (this.temp.length > 0) {
        this.temp.forEach((item) => {
          if (this.selectGoods.length > 0) {
            this.selectGoods.forEach((item1) => {
              if (item1.id === item.id) {
                this.$message.error('请选中没有的数据!')
                return false
              }
            })
          } else {
            // this.selectGoods = this.temp
            this.selectGoods.push(item)
            this.goodsClose()
            return false
          }
        })
        // this.selectGoods = this.selectGoods.concat(this.temp)
        this.temp.forEach((item) => {
          this.selectGoods.push(item)
        })
        //对象去重
        let obj = {}
        this.selectGoods = this.selectGoods.reduce(function(item, next) {
          obj[next.id] ? '' : (obj[next.id] = true && item.push(next))
          return item
        }, [])
        this.goodsClose()
        // this.selectGoods.concat(this.temp)
      } else {
        this.goodsClose()
      }

      // 弹出提示 只能选择实物、虚拟商品、不可选择挂件商品
      // if()
      // PHYSICALS_PRIZE
    },
    // 关闭商品弹窗
    goodsOnCancel() {
      this.goodsClose()
    },
    // 删除商品
    delGoods(list) {
      var count = 0
      this.selectGoods.forEach((item, index) => {
        if (item.id == list) {
          count = index
        }
      })
      this.selectGoods.splice(count, 1)
    },
    /* 导出 */
    exportFile() {
      this.$confirm('确定导出参与用户吗？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let url = partakeExport({ id: this.$route.query.id })
          let params = Object.assign({}, this.queryParams, this.searchParams)
          params.pageSize = 10000000
          this.downFile('get', url, params, '参与用户')
        })
        .catch(() => {})
    },

    /* 重置 */
    reset() {
      this.$refs['form'].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.partake {
  margin: 20px 30px 20px 30px;
  .right {
    margin-left: 40px !important;
  }
  .btn-box {
    margin-bottom: 30px;
  }
}
.show-goods-box {
  display: flex;
  flex-wrap: wrap;
  // flex-direction: row;
}
.show-goods {
  margin: 20px 0;
  .img {
    position: relative;
    .img-btn {
      position: absolute;
      top: -7px;
      right: 15px;
      cursor: pointer;
    }
  }
  img {
    width: 100px;
    height: 100px;
    margin-right: 20px;
  }
}

.goods {
  @import url('~@common/style/imgBox.less');
  .el-dialog .el-dialog__header {
    border-bottom: 1px solid #eee;
    padding: 7px 20px 6px;
  }
  .el-dialog span.el-dialog__title {
    font-size: 14px;
    color: #0d1636;
  }
  .el-dialog .el-dialog__headerbtn {
    top: 7px;
  }
  .el-dialog .el-dialog__footer .el-button {
    padding: 5px 30px;
    border-radius: 2px;
    font-family: 'Microsoft YaHei';
    font-size: 14px;
  }
  .el-button--success {
    background-color: #1dc8a4;
    border-color: #1dc8a4;
  }
  .el-button--success.is-active,
  .el-button--success:active {
    background-color: #1dc8a4 !important;
    border-color: #1dc8a4 !important;
    color: #fff;
  }

  .el-icon-circle-close {
    color: #fff;
  }

  .el-dialog {
    .page-box {
      margin-top: 20px;
      text-align: center;
      :deep(.el-pagination.is-background .el-pager li:hover) {
        color: #1dc8a4;
      }

      :deep(.el-pagination.is-background .el-pager li:not(.disabled).active) {
        line-height: 25px;
        background-color: #1dc8a4;
      }
      :deep(.el-pagination.is-background
          .el-pager
          li:not(.disabled).active:hover) {
        color: #fff !important;
      }
    }
  }
  :deep(.el-table__header-wrapper .el-checkbox) {
    display: none;
  }
  :deep(.el-image-viewer__close) {
    color: #fff;
  }
}

.goods-data .el-table__header-wrapper .el-checkbox {
  display: none;
}
</style>
